#include "server.h"

#include <cassert>

namespace app {

Server::Server() : server_accepter(*this) {
	sid = 0;
	server_type = 0;

	handler = NULL;
	accepter = NULL;

	server_manager = net::GetSocket();
}

Server::~Server() {
	if(accepter != NULL) {
		accepter->Close();
		accepter = NULL;
	}

	if(server_manager != NULL) {
		server_manager->Close();
		server_manager = NULL;
	}
}

void Server::ConnectToServerManager() {
	net::NetAddress address("127.0.0.1", 10001);

	server_manager->Connect(address);
	server_manager->SetHandler(this);
}

void Server::LoadConfigFile() {
	
}

void Server::Run() {
	if(handler == NULL) { 
		assert(false);
	}

	LoadConfigFile();

	/* 连接ServerManager */
	ConnectToServerManager();

	net::GetReactor()->Dispatch();
}

void Server::Terminate() {
	net::GetReactor()->Stop();
}

void Server::SetHandler(IServerHandler* handler) {
	this->handler = handler;
}

uint32_t Server::GetId() {
	return sid;	
}

uint32_t Server::GetServerType() {
	return server_type;
}

IServerHandler* Server::GetHandler() {
	return handler;
}

void Server::SetServerType(uint32_t server_type) {
	this->server_type = server_type;
}

void Server::AddWatcher(uint32_t server_type) {

}

void Server::OnRegisterServer(proto::RRegisterServer& packet) {
	if(packet.is_success == false) {
		Terminate();
		return ;
	}

	sid = packet.server_id;

	net::NetAddress address(packet.ip, packet.port);

	accepter = net::GetAccepter();
	accepter->Listen(address);
	accepter->SetHandler(&server_accepter);
}

void Server::OnRead(net::ISocket* socket) {
	pack::Request request(socket->GetInBuffer());		

	while(request.GetPack()) {
		switch(request.GetUri()) {
			case proto::RRegisterServer::URI : {
				proto::RRegisterServer packet;

				if(request.UnPack(&packet)) {
					OnRegisterServer(packet);
				}
			}break;
		}
	}
}

void Server::OnWrite(net::ISocket* socket) {

}

void Server::OnClose(net::ISocket* socket) {
	Terminate();
}

void Server::OnError(net::ISocket* socket, uint32_t error) {
	Terminate();
}

void Server::RegisterServer() {
	proto::PRegisterServer packet;
	pack::Request request(server_manager->GetOutBuffer());

	packet.server_type = server_type;

	request.Pack(&packet);
	server_manager->Send("", 0);
}

void Server::OnConnected(net::ISocket* socket) {
	/* 向ServerManager注册 */
	RegisterServer();
}

}
